package com.project.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.auth.model.process.Process;
import com.project.auth.model.process.ProcessTemplate;
import com.project.auth.model.system.SysUser;
import com.project.auth.service.MessageService;
import com.project.auth.service.ProcessService;
import com.project.auth.service.ProcessTemplateService;
import com.project.auth.service.SysUserService;
import com.project.security.custom.LoginUserInfoHelper;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Description
 * @Author XCM
 * @Date 2023/06/12 17:47
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private ProcessService processService;
    @Autowired
    private ProcessTemplateService processTemplateService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private WxMpService wxMpService;


    /**
     * 推送任务给审批人
     *
     * @param processId
     * @param userId
     * @param taskId
     */
    @Override
    public void pushPendingMessage(Long processId, Long userId, String taskId) {
        //根据processId查询流程信息
        Process process = processService.getById(processId);
        //根据userId查询审批人的信息
        SysUser user = sysUserService.getById(userId);
        //根据taskId查询模板信息
        ProcessTemplate template = processTemplateService.getById(process.getProcessTemplateId());
        //获得任务发起人的信息
        SysUser submitUser = sysUserService.getById(process.getUserId());

        //获得审批人的openId
        String openId = user.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            //TODO 测试用,添加默认值
            openId = "oDezb6UVhUJAPrPUZG8mlCGbT67E";
        }
        //设置发送信息模板
        WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                /**
                 * builder()的三个参数
                 *      1.给谁发送消息,openId
                 *      2.微信消息模板ID(用于接口调用)
                 *      3.点击消息后的跳转地址
                 */
                .toUser(openId)
                .templateId("T78ts0wtkU-qKZSfgUnrxa7zR1avBtSdBqGs6lNyfvA")
                .url("http://xiypgt.natappfree.cc/#/show/" + processId + "/" + taskId)
                .build();
        //将process流程中的数据转为map
        JSONObject jsonObject = JSON.parseObject(process.getFormValues());
        JSONObject formShowData = jsonObject.getJSONObject("formShowData");
        StringBuffer content = new StringBuffer();
        for (Map.Entry entry : formShowData.entrySet()) {
            content.append(entry.getKey()).append("：").append(entry.getValue()).append("\n ");
        }
        //设置模板消息中的参数值
        WxMpTemplateMessage first = wxMpTemplateMessage.addData(
                new WxMpTemplateData("first", submitUser.getName() + "提交了" + template.getName() + "审批申请，请注意查看。", "#272727"));
        wxMpTemplateMessage.addData(
                new WxMpTemplateData("keyword1", process.getProcessCode(), "#272727"));
        wxMpTemplateMessage.addData(
                new WxMpTemplateData("keyword2", new DateTime(process.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"), "#272727"));
        wxMpTemplateMessage.addData(
                new WxMpTemplateData("content", content.toString(), "#272727"));
        //调用方法发送消息
        try {
            String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
            System.out.println(msg);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 审批完成后发送消息
     *
     * @param processId
     * @param userId
     * @param status
     */
    public void pushProcessedMessage(Long processId, Long userId, Integer status) {
        Process process = processService.getById(processId);
        ProcessTemplate template = processTemplateService.getById(process.getProcessTemplateId());
        SysUser sysUser = sysUserService.getById(userId);
        SysUser currentSysUser = sysUserService.getById(LoginUserInfoHelper.getUserId());
        String openId = sysUser.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            openId = "oDezb6UVhUJAPrPUZG8mlCGbT67E";
        }
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("\tSy4NOC8r4TypWqoKccxMeEsF1a8uJIVP21Ie9f_gFTk")
                .url("http://xiypgt.natappfree.cc/#/show/" + processId + "/0")
                .build();
        JSONObject jsonObject = JSON.parseObject(process.getFormValues());
        JSONObject formShowData = jsonObject.getJSONObject("formShowData");
        StringBuffer content = new StringBuffer();
        for (Map.Entry entry : formShowData.entrySet()) {
            content.append(entry.getKey()).append("：").append(entry.getValue()).append("\n ");
        }
        templateMessage.addData(new WxMpTemplateData("first", "你发起的" + template.getName() + "审批申请已经被处理了，请注意查看。", "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword1", process.getProcessCode(), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword2", new DateTime(process.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword3", currentSysUser.getName(), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword4", status == 1 ? "审批通过" : "审批拒绝", status == 1 ? "#009966" : "#FF0033"));
        templateMessage.addData(new WxMpTemplateData("content", content.toString(), "#272727"));
        try {
            String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            System.out.println("推送消息返回：" + msg);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

}
